package com.ctshk.rpc.custom.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.custom.dto.*;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.custom.dto.inquiry.InquiryInfoDTO;
import com.ctshk.rpc.custom.dto.inquiry.InquiryInfoResp;
import com.ctshk.rpc.custom.dto.inquiry.InquiryListDTO;
import com.ctshk.rpc.custom.dto.quotation.QuotationTouristTypeDTO;
import com.ctshk.rpc.custom.entity.*;
import com.ctshk.rpc.custom.json.ContactTelephoneJson;
import com.ctshk.rpc.custom.json.InternalRemarkJson;
import com.ctshk.rpc.custom.mapper.*;
import com.ctshk.rpc.custom.req.ContactReq;
import com.ctshk.rpc.custom.req.TravelDaysReq;
import com.ctshk.rpc.custom.req.inquiry.*;
import com.ctshk.rpc.custom.req.QuotationTouristTypeReq;
import com.ctshk.rpc.custom.service.ICustomizedInquiryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.enums.MessageBusinessType;
import com.ctshk.rpc.system.enums.MessageSource;
import com.ctshk.rpc.system.req.SysMessageReq;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.system.service.ISystemMessageService;
import com.github.kfcfans.powerjob.client.OhMyClient;
import com.github.kfcfans.powerjob.common.response.ResultDTO;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 询价单 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-13
 */
@Slf4j
@DubboService
public class CustomizedInquiryServiceImpl extends ServiceImpl<CustomizedInquiryMapper, CustomizedInquiry> implements ICustomizedInquiryService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private CustomizedInquiryMapper customizedInquiryMapper;

    @Autowired
    private CustomizedQuotationTouristTypeMapper quotationTouristTypeMapper;

    @Autowired
    private CustomizedInquiryServiceRequireMapper inquiryServiceRequireMapper;

    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private ISysPermissionService sysPermissionService;
    @DubboReference
    private ISystemMessageService systemMessageService;

    @Autowired
    private CustomizedInquiryServiceRequireMapper customizedInquiryServiceRequireMapper;
    @Autowired
    private OperationLogMapper operationLogMapper;
    @Autowired
    private CustomizedQuotationMapper quotationMapper;

    @Value("${schedule.config.domain}")
    private String domain;

    @Value("${schedule.config.app-name}")
    private String appName;

    @Value("${schedule.config.password}")
    private String password;

    @Value("${schedule.job-id.order.custom}")
    private long jobIdOrder;

    @Override
    @Transactional(rollbackFor = Exception.class)
    // @GlobalTransactional
    public long add(InquiryReq inquiryReq, long userId) {
        //出发日期判断
        if (!inquiryReq.getDepartureDate().isAfter(LocalDate.now())){
            throw new BusinessException(SystemError.CUSTOM_3013);
        }
        if (!inquiryReq.getDepartureDate().isAfter(inquiryReq.getInquiryEndTime())){
            throw new BusinessException(SystemError.CUSTOM_3014);
        }
        if (inquiryReq.getDepartType() == null){
            inquiryReq.setDepartType(3);
        }
        CustomizedInquiry customizedInquiry = new CustomizedInquiry();
        // 拼接询价标题 生成規則為 (出發地)到(目的地)*天*晚
        String title = inquiryReq.getDeparturePlace() + "到" + inquiryReq.getDestination() + inquiryReq.getTravelDaysReq().getDays() + "天" + inquiryReq.getTravelDaysReq().getNights() + "晚";
        UserDTO userDTO = sysUserService.loadUserByParam(userId, 1);
        SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryOne(userDTO.getDeptId());
        // 生成询价单号 生成规则 XJ+部門代碼+年份(2位)+月份+日期+四位隨機字符
        String inquiryNumber = "XJ" + sysDepartmentDTO.getDeptCode() + DateUtil.fmtNum(LocalDate.now()) + RandomUtil.randomNumbers(4);
        Long inquiryId = SnowflakeIdWorker.nextId();
        customizedInquiry.setId(inquiryId);
        customizedInquiry.setInquiryTitle(title);
        customizedInquiry.setInquiryNumber(inquiryNumber);
        customizedInquiry.setDepartType(inquiryReq.getDepartType());
        customizedInquiry.setDestinationId(inquiryReq.getDestinationId());
        customizedInquiry.setDestination(inquiryReq.getDestination());
        customizedInquiry.setDeparturePlaceId(inquiryReq.getDeparturePlaceId());
        customizedInquiry.setDeparturePlace(inquiryReq.getDeparturePlace());
        customizedInquiry.setDepartureDate(inquiryReq.getDepartureDate());
        customizedInquiry.setTravelDays(inquiryReq.getTravelDaysReq().getDays());
        customizedInquiry.setNightDays(inquiryReq.getTravelDaysReq().getNights());
        int totalPeopleNum = 0;
        if (CollUtil.isNotEmpty(inquiryReq.getTouristTypes())) {
            totalPeopleNum = inquiryReq.getTouristTypes().stream().mapToInt(QuotationTouristTypeReq::getPeopleNum).sum();
        }
        customizedInquiry.setTotalPeopleNum(totalPeopleNum);
        customizedInquiry.setCapitaBudget(inquiryReq.getCapitaBudget());
        customizedInquiry.setOpId(inquiryReq.getOpId());
        UserDTO op = sysUserService.queryCacheUser(inquiryReq.getOpId());
        if (op != null){
            customizedInquiry.setOpNumber(op.getEmployeeNumber());
            customizedInquiry.setOpName(op.getFullName());
        }
        customizedInquiry.setInquiryEndTime(inquiryReq.getInquiryEndTime());
        customizedInquiry.setSalespersonId(userId);
        customizedInquiry.setSalespersonNumber(userDTO.getEmployeeNumber());
        customizedInquiry.setSalespersonName(userDTO.getFullName());
        customizedInquiry.setServiceRequireFiles(inquiryReq.getServiceRequireFiles());
        customizedInquiry.setCustomerListFiles(inquiryReq.getCustomerListFiles());
        customizedInquiry.setCustomerType(inquiryReq.getCustomerTypeReq().getCustomerType());
        customizedInquiry.setBigClientId(inquiryReq.getCustomerTypeReq().getBigClientId());
        customizedInquiry.setBigClientName(inquiryReq.getCustomerTypeReq().getBigClientName());
        customizedInquiry.setContactCnSurname(inquiryReq.getContactReq().getContactCnSurname());
        customizedInquiry.setContactCnName(inquiryReq.getContactReq().getContactCnName());
        customizedInquiry.setContactEnSurname(inquiryReq.getContactReq().getContactEnSurname());
        customizedInquiry.setContactEnName(inquiryReq.getContactReq().getContactEnName());
        customizedInquiry.setContactGender(inquiryReq.getContactGender());

        if (CollectionUtils.isNotEmpty(inquiryReq.getContactTelephoneJsonList())){
            customizedInquiry.setContactTelephones(JSON.toJSONString(inquiryReq.getContactTelephoneJsonList()));
        }
        customizedInquiry.setContactEmail(inquiryReq.getContactEmail());
        customizedInquiry.setInternalRemark(inquiryReq.getInternalRemark());
        Integer status = 1;
        if (inquiryReq.getReqType() == 1) {
            status = 1;
        } else if (inquiryReq.getReqType() == 2) {
            status = 2;
        }
        customizedInquiry.setInquiryStatus(status);
        customizedInquiry.setCreateId(userId);
        customizedInquiryMapper.insert(customizedInquiry);

        // 记录旅客类型(成人,老人,小孩等信息)
        if (CollUtil.isNotEmpty(inquiryReq.getTouristTypes())) {
            inquiryReq.getTouristTypes().forEach(quotationTouristTypeReq -> {
                CustomizedQuotationTouristType quotationTouristType = EntityUtil.copy(quotationTouristTypeReq, CustomizedQuotationTouristType.class);
                quotationTouristType.setId(SnowflakeIdWorker.nextId());
                quotationTouristType.setInquiryId(inquiryId);
                quotationTouristType.setMainDataId(quotationTouristTypeReq.getValue());
                quotationTouristType.setName(quotationTouristTypeReq.getLabel());
                quotationTouristType.setCreateId(userId);

                quotationTouristTypeMapper.insert(quotationTouristType);
            });
        }

        // 记录服务要求
        if (CollUtil.isNotEmpty(inquiryReq.getServiceRequires())) {
            inquiryReq.getServiceRequires().forEach(inquiryServiceRequireReq -> {
                CustomizedInquiryServiceRequire inquiryServiceRequire = EntityUtil.copy(inquiryServiceRequireReq, CustomizedInquiryServiceRequire.class);
                inquiryServiceRequire.setId(SnowflakeIdWorker.nextId());
                inquiryServiceRequire.setInquiryId(inquiryId);
                inquiryServiceRequire.setCreateId(userId);

                inquiryServiceRequireMapper.insert(inquiryServiceRequire);
            });
        }

        //发送系统通知
        sendSysMessage(inquiryId,inquiryNumber, op.getId(), userId,"发布询价");

        return inquiryId;
    }

    /**
     * 编辑询价单
     * @param inquiryReq
     * @return
     */
    @Override
    public long edit(InquiryReq inquiryReq, long userId) {

        //出发日期判断
        if (!inquiryReq.getDepartureDate().isAfter(LocalDate.now())){
            throw new BusinessException(SystemError.CUSTOM_3013);
        }
        if (!inquiryReq.getDepartureDate().isAfter(inquiryReq.getInquiryEndTime())){
            throw new BusinessException(SystemError.CUSTOM_3014);
        }

        CustomizedInquiry customizedInquiry = new CustomizedInquiry();
        // 拼接询价标题  (出發地)到(目的地)*天*晚
        String title = inquiryReq.getDeparturePlace() + "到" + inquiryReq.getDestination() + inquiryReq.getTravelDaysReq().getDays() + "天" + inquiryReq.getTravelDaysReq().getNights() + "晚";
        UserDTO userDTO = sysUserService.loadUserByParam(userId, 1);
        Long inquiryId = inquiryReq.getId();
        customizedInquiry.setId(inquiryId);
        customizedInquiry.setInquiryTitle(title);
        customizedInquiry.setDestinationId(inquiryReq.getDestinationId());
        customizedInquiry.setDestination(inquiryReq.getDestination());
        customizedInquiry.setDeparturePlaceId(inquiryReq.getDeparturePlaceId());
        customizedInquiry.setDeparturePlace(inquiryReq.getDeparturePlace());
        customizedInquiry.setDepartureDate(inquiryReq.getDepartureDate());
        customizedInquiry.setTravelDays(inquiryReq.getTravelDaysReq().getDays());
        customizedInquiry.setNightDays(inquiryReq.getTravelDaysReq().getNights());
        int totalPeopleNum = 0;
        if (CollUtil.isNotEmpty(inquiryReq.getTouristTypes())) {
            totalPeopleNum = inquiryReq.getTouristTypes().stream().mapToInt(QuotationTouristTypeReq::getPeopleNum).sum();
        }
        customizedInquiry.setTotalPeopleNum(totalPeopleNum);
        customizedInquiry.setCapitaBudget(inquiryReq.getCapitaBudget());
        customizedInquiry.setOpId(inquiryReq.getOpId());
        UserDTO op = sysUserService.queryCacheUser(inquiryReq.getOpId());
        if (op != null){
            customizedInquiry.setOpNumber(op.getEmployeeNumber());
            customizedInquiry.setOpName(op.getFullName());
        }
        customizedInquiry.setInquiryEndTime(inquiryReq.getInquiryEndTime());
        customizedInquiry.setSalespersonId(userId);
        customizedInquiry.setSalespersonNumber(userDTO.getEmployeeNumber());
        customizedInquiry.setSalespersonName(userDTO.getFullName());
        customizedInquiry.setServiceRequireFiles(inquiryReq.getServiceRequireFiles());
        customizedInquiry.setCustomerListFiles(inquiryReq.getCustomerListFiles());
        customizedInquiry.setCustomerType(inquiryReq.getCustomerTypeReq().getCustomerType());
        customizedInquiry.setBigClientId(inquiryReq.getCustomerTypeReq().getBigClientId());
        customizedInquiry.setBigClientName(inquiryReq.getCustomerTypeReq().getBigClientName());
        customizedInquiry.setContactCnSurname(inquiryReq.getContactReq().getContactCnSurname());
        customizedInquiry.setContactCnName(inquiryReq.getContactReq().getContactCnName());
        customizedInquiry.setContactEnSurname(inquiryReq.getContactReq().getContactEnSurname());
        customizedInquiry.setContactEnName(inquiryReq.getContactReq().getContactEnName());
        customizedInquiry.setContactGender(inquiryReq.getContactGender());

        if (CollectionUtils.isNotEmpty(inquiryReq.getContactTelephoneJsonList())){
            customizedInquiry.setContactTelephones(JSON.toJSONString(inquiryReq.getContactTelephoneJsonList()));
        }

        customizedInquiry.setContactEmail(inquiryReq.getContactEmail());
        customizedInquiry.setInternalRemark(inquiryReq.getInternalRemark());
        Integer status = 1;
        if (inquiryReq.getReqType() == 1) {
            status = 1;
        } else if (inquiryReq.getReqType() == 2) {
            status = 2;
        }
        customizedInquiry.setInquiryStatus(status);
        customizedInquiry.setCreateId(userId);
        customizedInquiryMapper.updateById(customizedInquiry);

        // 记录旅客类型(成人,老人,小孩等信息)
        if (CollUtil.isNotEmpty(inquiryReq.getTouristTypes())) {
            // 根据inquiryId删除旅客记录表所有记录
            QueryWrapper<CustomizedQuotationTouristType> touristTypeWrapper = new QueryWrapper<>();
            touristTypeWrapper.eq("inquiry_id",inquiryId);
            CustomizedQuotationTouristType touristType = new CustomizedQuotationTouristType();
            touristType.setIsDeleted(1);
            touristType.setModifiedId(userId);
            quotationTouristTypeMapper.update(touristType,touristTypeWrapper);

            inquiryReq.getTouristTypes().forEach(quotationTouristTypeReq -> {
                CustomizedQuotationTouristType quotationTouristType = EntityUtil.copy(quotationTouristTypeReq, CustomizedQuotationTouristType.class);
                quotationTouristType.setId(SnowflakeIdWorker.nextId());
                quotationTouristType.setInquiryId(inquiryId);
                quotationTouristType.setMainDataId(quotationTouristTypeReq.getValue());
                quotationTouristType.setName(quotationTouristTypeReq.getLabel());
                quotationTouristType.setCreateId(userId);

                quotationTouristTypeMapper.insert(quotationTouristType);
            });
        }

        // 记录服务要求
        if (CollUtil.isNotEmpty(inquiryReq.getServiceRequires())) {
            // 根据inquiryId删除记录服务表所有记录
            QueryWrapper<CustomizedInquiryServiceRequire> inquiryWrapper = new QueryWrapper<>();
            inquiryWrapper.eq("inquiry_id",inquiryId);
            CustomizedInquiryServiceRequire inquiryService= new CustomizedInquiryServiceRequire();
            inquiryService.setIsDeleted(1);
            inquiryService.setModifiedId(userId);
            inquiryServiceRequireMapper.update(inquiryService,inquiryWrapper);


            inquiryReq.getServiceRequires().forEach(inquiryServiceRequireReq -> {
                CustomizedInquiryServiceRequire inquiryServiceRequire = EntityUtil.copy(inquiryServiceRequireReq, CustomizedInquiryServiceRequire.class);
                inquiryServiceRequire.setId(SnowflakeIdWorker.nextId());
                inquiryServiceRequire.setInquiryId(inquiryId);
                inquiryServiceRequire.setCreateId(userId);

                inquiryServiceRequireMapper.insert(inquiryServiceRequire);
            });
        }

        //发送系统通知
        sendSysMessage(inquiryId,customizedInquiry.getInquiryNumber(), op.getId(), userId,"发布询价");

        return inquiryId;
    }

    /**
     * 询价单详情
     * @param inquiryInfoReq
     * @return
     */
    @Override
    public Result<InquiryInfoDTO> query(InquiryInfoReq inquiryInfoReq) {
        //获取询价单详情
        QueryWrapper<CustomizedInquiry> inquiryWrapper = new QueryWrapper<>();
        inquiryWrapper.eq("inquiry_number",inquiryInfoReq.getInquiryNumber());
        inquiryWrapper.eq("is_deleted",0);
        CustomizedInquiry inquiry = customizedInquiryMapper.selectOne(inquiryWrapper);
        if (inquiry == null){
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        InquiryInfoDTO inquiryInfoDTO = EntityUtil.copy(inquiry, InquiryInfoDTO.class);
        if (StringUtils.isNotBlank(inquiry.getInternalRemark())){
            try {
                InternalRemarkJson internalRemarkJson = JSON.parseObject(inquiry.getInternalRemark(), InternalRemarkJson.class);
                inquiryInfoDTO.setInternalRemark(internalRemarkJson.getInternalRemark());
            }catch (Exception e){
                inquiryInfoDTO.setInternalRemark(inquiry.getInternalRemark());
            }
        }
        if (StringUtils.isNotBlank(inquiry.getThemeJson())){
            List<InquiryRequireReq> themeJson = JSON.parseArray(inquiry.getThemeJson(),InquiryRequireReq.class);
            inquiryInfoDTO.setThemeJson(themeJson);
        }
        inquiryInfoDTO.setId(inquiry.getId());
        if (StringUtils.isNotBlank(inquiry.getContactTelephones())){
            inquiryInfoDTO.setContactTelephoneJsonList(JSON.parseArray(inquiry.getContactTelephones(), ContactTelephoneJson.class));
        }
        if (inquiry.getTravelType() == null){
            //联系人
            ContactReq contactReq = new ContactReq();
            contactReq.setContactCnSurname(inquiry.getContactCnSurname());
            contactReq.setContactCnName(inquiry.getContactCnName());
            contactReq.setContactEnSurname(inquiry.getContactEnSurname());
            contactReq.setContactEnName(inquiry.getContactEnName());
            inquiryInfoDTO.setContactReq(contactReq);
        }

        //出行天数
        TravelDaysReq travelDaysReq = new TravelDaysReq();
        travelDaysReq.setDays(inquiry.getTravelDays());
        travelDaysReq.setNights(inquiry.getNightDays());
        inquiryInfoDTO.setTravelDaysReq(travelDaysReq);
        //获取部门和联系电话
        if (inquiry.getOpId() != null){
            UserDTO opDTO = sysUserService.queryCacheUser(inquiry.getOpId());
            if (opDTO != null){
                inquiryInfoDTO.setOpDepart(opDTO.getDept());
                inquiryInfoDTO.setOpPhone(opDTO.getTelephone());
            }
        }
        if (inquiry.getSalespersonId() != null){
            UserDTO salesDTO = sysUserService.queryCacheUser(inquiry.getSalespersonId());
            if (salesDTO != null){
                inquiryInfoDTO.setSalespersonDepart(salesDTO.getDept());
                inquiryInfoDTO.setSalespersonPhone(salesDTO.getTelephone());
            }
        }
        if (inquiry.getBigClientId() != null){
            UserDTO bigClientDTO = sysUserService.queryCacheUser(inquiry.getSalespersonId());
            if (bigClientDTO != null){
                inquiryInfoDTO.setBigClientDepart(bigClientDTO.getDept());
            }
        }
        //旅客类型和人数
        QueryWrapper<CustomizedQuotationTouristType> touristTypeWrapper = new QueryWrapper<>();
        touristTypeWrapper.eq("inquiry_id",inquiry.getId());
        touristTypeWrapper.eq("is_deleted",0);
        touristTypeWrapper.isNull("quotation_id");
        touristTypeWrapper.isNull("package_id");
        List<CustomizedQuotationTouristType> touristTypeList = quotationTouristTypeMapper.selectList(touristTypeWrapper);
        List<QuotationTouristTypeDTO> touristTypeDTOList = new ArrayList<>();
        touristTypeList.forEach(touristType -> {
            QuotationTouristTypeDTO touristTypeDTO = EntityUtil.copy(touristType, QuotationTouristTypeDTO.class);
            touristTypeDTO.setValue(touristType.getMainDataId());
            touristTypeDTO.setLabel(touristType.getName());
            touristTypeDTOList.add(touristTypeDTO);
        });
        inquiryInfoDTO.setTouristTypes(touristTypeDTOList);
        //查询服务要求列表
        List<ServiceRequireDTO> serviceRequireDtoList = customizedInquiryServiceRequireMapper.queryListByInquiryId(inquiry.getId());
        inquiryInfoDTO.setServiceRequires(serviceRequireDtoList);
        //查询操作记录
        QueryWrapper<OperationLog> wrapper = new QueryWrapper<>();
        wrapper.eq("model", OperationLogModel.CUSTOM.getCode());
        wrapper.eq("record_id",inquiry.getId());
        List<OperationLog> logList = operationLogMapper.selectList(wrapper);
        List<OperationLogDTO> operationLogDtoList = new ArrayList<>();
        logList.forEach(log -> {
            OperationLogDTO logDto = EntityUtil.copy(log, OperationLogDTO.class);
            operationLogDtoList.add(logDto);
        });
        inquiryInfoDTO.setOperationLogDtoList(operationLogDtoList);
        return Result.success(inquiryInfoDTO);
    }

    /**
     * 询价单列表
     * @param inquiryListReq
     * @param currentUser
     * @return
     */
    @Override
    public PageResponse<InquiryListDTO> list(InquiryListReq inquiryListReq, TokenUser currentUser) {
        /*if (inquiryListReq.getDepartType() == null){
            inquiryListReq.setDepartType(3);
        }*/
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(inquiryListReq.getMenuId(), currentUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        IPage<CustomizedInquiry> inquiryIPage = new Page<>(inquiryListReq.getPageNo(),inquiryListReq.getPageSize());
        if (inquiryListReq.getInquiryStatus() == null){
            inquiryListReq.setInquiryStatus(NumberConstant.ZERO.getValue());
        }
        if (inquiryListReq.getQueryType().intValue() == NumberConstant.TWO.getValue()){
            //预订中心
            LocalDate begin = null;
            LocalDate end = null;
            if (StringUtils.isNotBlank(inquiryListReq.getBeginDate())){
                begin = LocalDate.parse(inquiryListReq.getBeginDate());
                if (StringUtils.isNotBlank(inquiryListReq.getEndDate())){
                    end = LocalDate.parse(inquiryListReq.getEndDate());
                }
            }
            //出行天数
            String travelDays = null;
            //天数查询类型(0 不查询,1：1天,2：多个,3：10天以上)
            Integer type = NumberConstant.ZERO.getValue();
            if (inquiryListReq.getTravelDays() != null && inquiryListReq.getTravelDays().size() > 0 && inquiryListReq.getTravelDays().size() != NumberConstant.FIVE.getValue()){
                if (inquiryListReq.getTravelDays().size() == NumberConstant.ONE.getValue()){
                    //单选
                    if(StrConstant.NINETYNINE.getValue().equals(inquiryListReq.getTravelDays().get(0).toString())){
                        //10天以上
                        travelDays = NumberConstant.TEN.getValue().toString();
                        type = NumberConstant.THREE.getValue();
                    }else if(!inquiryListReq.getTravelDays().get(0).toString().contains(",")){
                        //非10天以上 = 1天
                        travelDays = NumberConstant.ONE.getValue().toString();
                        type = NumberConstant.ONE.getValue();
                    }else{
                        travelDays = inquiryListReq.getTravelDays().get(0).toString();
                        type = NumberConstant.TWO.getValue();
                    }
                }else{
                    //多个
                    type = NumberConstant.TWO.getValue();
                    for (int i=0;i<inquiryListReq.getTravelDays().size();i++){
                        String str = (String) inquiryListReq.getTravelDays().get(i);
                        travelDays = travelDays + "," + str;
                    }
                }
            }
            //询价单状态(0 全部,1 未询价,2 未处理,3 已超时,4 已同意,5 已拒绝,6 继续询价,7 已报价,8 待开团,9 已开团)
            Integer quotationStatus = null;
            Integer inquiryStatus = null;
            if (inquiryListReq.getInquiryStatus().intValue() > NumberConstant.FIVE.getValue()){
                quotationStatus = inquiryListReq.getInquiryStatus() - 5;
            }else{
                inquiryStatus = inquiryListReq.getInquiryStatus();
            }
            //TODO 权限检验
            boolean permision = true;
            /*if (GlobalConstants.Role.isAdmin(currentUser.getUsername())){
                permision = false;
            }*/
            try{
                //封装sql参数
                InquiryListSqlReq sqlReq = EntityUtil.copy(inquiryListReq,InquiryListSqlReq.class);
                sqlReq.setBeginDate(begin);
                sqlReq.setEndDate(end);
                if (!Objects.equals(currentUser.getId(),1344284712813568L)){
                    sqlReq.setOpId(currentUser.getId());
                    permision = false;
                }
                sqlReq.setQuotationStatus(quotationStatus);
                sqlReq.setQueryType(2);
                sqlReq.setType(type);
                sqlReq.setTravelDays(travelDays);
            //    sqlReq.setDepartType(inquiryListReq.getDepartType());
                sqlReq.setPermision(permision);
                sqlReq.setPermisionList(permissionResult.getData());
                inquiryIPage = customizedInquiryMapper.queryListByQuatationStatus(sqlReq,inquiryIPage);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            //产品中心
            // 分页条件查询
            QueryWrapper<CustomizedInquiry> wrapper = new QueryWrapper<>();
            wrapper.like(StringUtils.isNotBlank(inquiryListReq.getInquiryTitle()),"inquiry_title",inquiryListReq.getInquiryTitle());
            wrapper.like(StringUtils.isNotBlank(inquiryListReq.getInquiryNumber()),"inquiry_number",inquiryListReq.getInquiryNumber());
            if (StringUtils.isNotBlank(inquiryListReq.getBeginDate())){
                LocalDate beginDate = LocalDate.parse(inquiryListReq.getBeginDate());
                wrapper.ge("gmt_create",beginDate);
            }
       //     wrapper.eq("depart_type", inquiryListReq.getDepartType());
            wrapper.eq("is_deleted",0);
            if (inquiryListReq.getQueryType().intValue() == NumberConstant.ONE.getValue()){
                wrapper.ne("inquiry_status",1);
            }
            wrapper.eq(inquiryListReq.getBigClientId() != null,"big_client_id",inquiryListReq.getInquiryTitle());
            wrapper.eq(inquiryListReq.getSalespersonId() != null,"salesperson_id",inquiryListReq.getSalespersonId());
            wrapper.eq(inquiryListReq.getInquiryStatus() != null && inquiryListReq.getInquiryStatus() != 0,"inquiry_status",inquiryListReq.getInquiryStatus());
            wrapper.eq(inquiryListReq.getOpId() != null,"op_id",inquiryListReq.getOpId());
            wrapper.lambda().in(!GlobalConstants.Role.isAdmin(currentUser.getUsername()), CustomizedInquiry::getCreateId, permissionResult.getData());
            //查询类型(1 产品中心，2 定制中心)
            if (!Objects.equals(currentUser.getId(),1344284712813568L)){
                if (inquiryListReq.getQueryType().intValue() == NumberConstant.ONE.getValue()){
                    wrapper.or();
                    wrapper.eq("op_id",currentUser.getId());
                    wrapper.or();
                    wrapper.eq("salesperson_id",currentUser.getId());
                }
            }
            wrapper.orderByDesc("gmt_create");
            Page<CustomizedInquiry> iPage = new Page<>(inquiryListReq.getPageNo(), inquiryListReq.getPageSize());
            inquiryIPage = customizedInquiryMapper.selectPage(iPage, wrapper);
        }
        if (CollectionUtils.isEmpty(inquiryIPage.getRecords())) {
            return PageResponse.empty(inquiryIPage.getCurrent());
        }
        List<InquiryListDTO> listDtoList = new ArrayList<>();
        inquiryIPage.getRecords().forEach(inquiry -> {
            InquiryListDTO inquiryListDto = EntityUtil.copy(inquiry, InquiryListDTO.class);
            // 获取部门
            if (inquiry.getOpId() != null) {
                UserDTO opDTO = sysUserService.queryCacheUser(inquiry.getOpId());
                if (opDTO != null){
                    inquiryListDto.setOpDepart(opDTO.getDept());
                }
            }
            if (inquiry.getSalespersonId() != null) {
                UserDTO salesDTO = sysUserService.queryCacheUser(inquiry.getSalespersonId());
                if (salesDTO != null){
                    inquiryListDto.setSalespersonDepart(salesDTO.getDept());
                }
            }
            if (inquiry.getInquiryStatus().intValue() == NumberConstant.SIX.getValue() || inquiry.getInquiryStatus().intValue() == NumberConstant.SEVEN.getValue()){
                CustomizedQuotation quotation = quotationMapper.selectById(inquiry.getQuotationId());
                if (quotation != null){
                    inquiryListDto.setQuotationNumber(quotation.getQuotationNumber());
                }
            }
            listDtoList.add(inquiryListDto);
        });
        PageResponse<InquiryListDTO> result = new PageResponse<>(listDtoList, inquiryIPage.getCurrent() == 1, inquiryIPage.getTotal() <= (inquiryIPage.getCurrent() * inquiryIPage.getSize()), inquiryIPage.getTotal(), inquiryIPage.getCurrent(), inquiryIPage.getSize());
        return result;
    }

    /**
     * 接受询价
     * @param inquiryInfoReq
     * @return
     */
    @Override
    public Result acceptInquiry(InquiryInfoReq inquiryInfoReq) {
        //获取询价单详情
        QueryWrapper<CustomizedInquiry> wrapper = new QueryWrapper<>();
        wrapper.eq("inquiry_number",inquiryInfoReq.getInquiryNumber());
        wrapper.eq("is_deleted",0);
        CustomizedInquiry inquiry = customizedInquiryMapper.selectOne(wrapper);
        if (inquiry == null){
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        if (inquiry.getInquiryStatus().intValue() != NumberConstant.TWO.getValue()){
            throw new BusinessException(SystemError.CUSTOM_3001);
        }
        //已同意
        inquiry.setInquiryStatus(NumberConstant.FOUR.getValue());
        int update = customizedInquiryMapper.updateById(inquiry);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(inquiry.getId());
    }

    /**
     * 拒绝询价
     * @param inquiryRefuseReq
     * @return
     */
    @Override
    public Result refuseInquiry(InquiryRefuseReq inquiryRefuseReq) {
        //获取询价单详情
        QueryWrapper<CustomizedInquiry> wrapper = new QueryWrapper<>();
        wrapper.eq("inquiry_number",inquiryRefuseReq.getInquiryNumber());
        wrapper.eq("is_deleted",0);
        CustomizedInquiry inquiry = customizedInquiryMapper.selectOne(wrapper);
        if (inquiry == null){
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        if (inquiry.getInquiryStatus().intValue() != NumberConstant.TWO.getValue()){
            throw new BusinessException(SystemError.CUSTOM_3001);
        }
        //已拒绝
        inquiry.setInquiryStatus(NumberConstant.FIVE.getValue());
        inquiry.setRefuseRemark(inquiryRefuseReq.getRefuseRemark());
        inquiry.setRefuseTime(LocalDateTime.now());
        int update = customizedInquiryMapper.updateById(inquiry);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(inquiry.getId());
    }

    /**
     * 下载文件
     * @param inquiryTypeReq
     * @param request
     * @param response
     */
    @Override
    public void downLoadFile(InquiryTypeReq inquiryTypeReq, HttpServletRequest request, HttpServletResponse response){
        //获取询价单详情
        QueryWrapper<CustomizedInquiry> wrapper = new QueryWrapper<>();
        wrapper.eq("inquiry_number",inquiryTypeReq.getInquiryNumber());
        wrapper.eq("is_deleted",0);
        CustomizedInquiry inquiry = customizedInquiryMapper.selectOne(wrapper);
        if (inquiry == null){
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        //文件地址-默认旅客需求
        String fileUrl = inquiry.getServiceRequireFiles();
        //文件名称-默认旅客需求
        String fileName = "旅客需求.ppt";
        if (inquiryTypeReq.getType().intValue() == NumberConstant.TWO.getValue()){
            //旅客名单
            fileUrl = inquiry.getCustomerListFiles();
            fileName = "名單.xlsx";
        }
        if (StringUtils.isEmpty(fileUrl)){
            throw new BusinessException(SystemError.CUSTOM_3002);
        }
        String directory = System.getProperty("user.dir");
        File file = new File(directory+"/"+fileUrl);
        try{
            InputStream inStream = new FileInputStream(file);
            //获得浏览器代理信息
            final String userAgent = request.getHeader("USER-AGENT");
            //判断浏览器代理并分别设置响应给浏览器的编码格式
            String finalFileName = null;
            if(StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent,"Trident")){//IE浏览器
                finalFileName = URLEncoder.encode(fileName,"UTF8");
                System.out.println("IE浏览器");
            }else if(StringUtils.contains(userAgent, "Mozilla")){
                //google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                //其他浏览器
                finalFileName = URLEncoder.encode(fileName,"UTF8");
            }
            response.reset();
            //告知浏览器下载文件，而不是直接打开，浏览器默认为打开
            //response.setContentType("application/multipart/form-data");
            String mineType = request.getServletContext().getMimeType(finalFileName);
            response.setContentType(mineType);
            //下载文件的名称
            response.addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
            response.getOutputStream().close();
        }catch(Exception e) {
            throw new BusinessException(SystemError.CUSTOM_3004);
        }finally{
            if (file.exists()){
                file.delete();
            }
        }
    }

    /**
     * 询价列表操作
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result changeStatus(InquiryChangeStatusReq req, Long userId) {
        //获取询价
        CustomizedInquiry inquiry = customizedInquiryMapper.selectById(req.getInquiryId());
        if (inquiry == null){
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        //操作类型（1 发起询价,2 确认报价,3 继续询价）
        //询价单状态(1 未询价 2 未处理 3 已超时 4 已同意 5 已拒绝 6 继续询价 7 已报价 8 待开团9 已开团)
        if (req.getType().intValue() == NumberConstant.ONE.getValue()){
            if (inquiry.getInquiryStatus().intValue() != NumberConstant.ONE.getValue() && inquiry.getInquiryStatus().intValue() != NumberConstant.FIVE.getValue()){
                throw new BusinessException(SystemError.CUSTOM_3001);
            }
            inquiry.setInquiryStatus(2);
        }else if (req.getType().intValue() == NumberConstant.TWO.getValue()){
            if (inquiry.getInquiryStatus().intValue() != NumberConstant.SEVEN.getValue()){
                throw new BusinessException(SystemError.CUSTOM_3001);
            }
            inquiry.setInquiryStatus(8);
        }else{
            if (inquiry.getInquiryStatus().intValue() != NumberConstant.SEVEN.getValue()){
                throw new BusinessException(SystemError.CUSTOM_3001);
            }
            inquiry.setInquiryStatus(6);
            if (StringUtils.isNotBlank(req.getFeedbackInfo())){
                inquiry.setFeedbackInfo(req.getFeedbackInfo());
            }
            if (inquiry.getQuotationId() != null){
                //报价单改为继续询价状态
                CustomizedQuotation quotation = quotationMapper.selectById(inquiry.getQuotationId());
                if (quotation != null){
                    quotation.setQuotationStatus(NumberConstant.ONE.getValue());
                    int update = quotationMapper.updateById(quotation);
                    if (update < 0){
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
        }
        inquiry.setModifiedId(userId);
        int update = customizedInquiryMapper.updateById(inquiry);
        if (update < 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(inquiry.getId());
    }

    @Override
    public List<InquiryInfoDTO> expiresList() {
        List<CustomizedInquiry> dtos = customizedInquiryMapper.selectList(Wrappers.<CustomizedInquiry>lambdaQuery()
                .between(CustomizedInquiry::getInquiryEndTime, LocalDate.now(), LocalDate.now().plusDays(1))
                .eq(CustomizedInquiry::getInquiryStatus,2)
                .eq(CustomizedInquiry::getIsDeleted,0));
        return EntityUtil.copyList(dtos, InquiryInfoDTO.class);
    }

    @Override
    public Result expires(long id) {
        CustomizedInquiry inquiry = customizedInquiryMapper.selectById(id);
        if (inquiry == null || inquiry.getIsDeleted() == 1){
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        inquiry.setInquiryStatus(3);
        customizedInquiryMapper.updateById(inquiry);
        return Result.success();
    }

    /**
     * 用户下单service
     * @param id
     */
    @Override
    public void expiresTaskDemo(long id) {
        //。。。。 上面是用户下单业务操作
        // 下单业务完成后调用任务执行超时失效操作
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        // 延迟时间,单位毫秒,10秒后执行
        long delayMS = 10000L;
        OhMyClient taskClient = new OhMyClient(domain, appName, password);
        ResultDTO<Long> resultTask = taskClient.runJob(jobIdOrder, jsonObject.toJSONString(), delayMS);

        if (resultTask.isSuccess()) {
            // 任务执行成功
            redisTemplate.opsForValue().set(RedisConstants.ORDER_INSTANCELD_KEY + id, resultTask.getData(), delayMS, TimeUnit.MILLISECONDS);
        }
    }

    @Override
    public void payTaskDemo(long id) {
        //。。。。 上面是用户付款业务操作
        // 付款业务完成后调用取消任务执行超时失效操作
        Long instanceId = (Long) redisTemplate.opsForValue().get(RedisConstants.ORDER_INSTANCELD_KEY + id);
        OhMyClient taskClient = new OhMyClient(domain, appName, password);
        ResultDTO<Void> resultTask = taskClient.cancelInstance(instanceId);

        if (resultTask.isSuccess()) {
            // 取消任务执行成功
            log.info("订单付款成功,取消订单失效任务操作,订单id[{}],任务实例id[{}]", id, instanceId);
        }
    }

    /**
     * 发送系统通知
     * @param businessId
     * @param businessOrderNo
     * @param receivingUserId
     * @param userId
     */
    public void sendSysMessage(Long businessId,String businessOrderNo,Long receivingUserId,Long userId,String title){
        //发送系统通知
        SysMessageReq addReq = new SysMessageReq();
        addReq.setType(2);
        addReq.setBusinessType(MessageBusinessType.INQUIRY_NOTICE.getCode());
        addReq.setSource(MessageSource.PRODUCT_CENTER.getMsg());
        addReq.setTitle(title);
        addReq.setBusinessId(businessId);
        addReq.setBusinessOrderNo(businessOrderNo);
        addReq.setReceivingUserId(receivingUserId);
        addReq.setSendingTime(LocalDateTime.now());
        try {
            systemMessageService.add(addReq, userId);
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_419);
        }
    }

}
